<?php


namespace App\Services\Repositories\Admin;


use App\Models\Admin\StoreAdmin;
use App\Services\Repositories\Connector\AdminInterface;
use App\Services\Utils\ApiChecker;
use Tymon\JWTAuth\Contracts\JWTSubject;


class StoreAdminRepository implements AdminInterface
{
    use ApiChecker;

    /**
     * @param string $account
     * @return StoreAdmin
     * @throws \Exception
     */
    public function findAdmin(string $account): StoreAdmin
    {
        /** @var StoreAdmin $admin */
        $admin = (new StoreAdmin)
            ->where('account', $account)
            ->with('store.customer.categories')
            ->first();

        $this->checkIsTrue($admin, trans('middleware.account_not_found'));
        $this->checkIsTrue($admin->isSuperMan(), trans('middleware.account_must_be_super_admin'));
        $this->checkUnless($admin->is_deleted, trans('middleware.account_disabled'));
        $this->checkIsTrue($admin->store, trans('middleware.store_admin.store_missing'));
        $this->checkUnless($admin->store->is_deleted, trans('middleware.store_admin.store_disabled'));
        $this->checkIsTrue($admin->store->customer, trans('middleware.customer_admin.customer_missing'));
        $this->checkUnless($admin->store->customer->is_deleted, trans('middleware.customer_admin.customer_disabled'));

        return $admin;
    }

    /**
     * @param JWTSubject $admin
     * @return StoreAdmin | JWTSubject
     */
    public function loginAdminInfo(JWTSubject $admin)
    {
        /** @var StoreAdmin $admin */
        $admin->provider_type = $admin->store->customer->provider_type ?? null;
        $admin->has_hair = $admin->store->customer->has_hair ?? null;
        $admin->has_youzan = $admin->store->has_youzan ?? null;
        $admin->has_youzan_authorize = $admin->store->youzan_authorizer_id ?? null;
        /**
         * @since v2.3.3 - 无公众号，后台不显示绑定微信
         */
        $admin->has_wx = (bool)$admin->store->customer->authorizer_id;
        $admin->customer_id = $admin->store->customer_id ?? null;

        return $admin;
    }
}